package com.example.xlzx.interceptor;



import com.example.xlzx.exception.xlzxException;
import com.example.xlzx.login.LoginUser;
import com.example.xlzx.login.LoginUserHolder;
import com.example.xlzx.result.ResultCodeEnum;
import com.example.xlzx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        String token = request.getHeader("access-token");
        Claims claims = JwtUtil.parseToken(token);
        Long parentId = claims.get("parentId", Long.class);
        String parentPhone = claims.get("parentPhone", String.class);

        //redis验证
        String cachedToken = redisTemplate.opsForValue().get(String.valueOf(parentId));
        if (cachedToken != null && cachedToken.equals(token)) {
            LoginUserHolder.setLoginUser(new LoginUser(parentId,parentPhone));
            return true;
        } else {
            // Token 已过期或已经在其他地方登录
            throw new xlzxException(ResultCodeEnum.LOGGED_IN_ON_ANOTHER_DEVICE);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}